package com.kmzx.one.project.controller;

import com.kmzx.one.common.utils.MyAssert;
import com.kmzx.one.project.entity.UserOrder;
import com.kmzx.one.project.net.BaseResult;
import com.kmzx.one.project.net.OrderParam;
import com.kmzx.one.project.others.dto.OrderBackInfo;
import com.kmzx.one.project.others.dto.UserCertInfo;
import com.kmzx.one.project.others.dto.UserOrderFinalInfo;
import com.kmzx.one.project.others.dto.UserOrderMoreInfo;
import com.kmzx.one.project.others.dto.UserOrderOutInfo;
import com.kmzx.one.project.others.dto.WikiH5PayResponse;
import com.kmzx.one.project.service.UserAddressService;
import com.kmzx.one.project.service.UserOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Api(tags = "快美甄选_[ 用户_订单_接口 ]")
@RestController
public class UserOrderController extends BaseController {
    @Autowired
    UserOrderService userOrderService;
    @Autowired
    UserAddressService userAddressService;


    /**
     * 我的订单
     *
     * @param userId
     * @return
     */
    @ApiOperation(value = "1.我的订单列表", notes = "我的订单列表")
    @GetMapping(value = "order/mine")
    public BaseResult listMyOrder(String userId, Integer pageNum, Integer pageSize, Integer kinds) {
        try {
            MyAssert.notNullObject(userId, "userId 为null");
            MyAssert.notNullObject(pageNum, "pageNum 为null");
            MyAssert.notNullObject(pageSize, "pageSize 为null");
            MyAssert.notNullObject(kinds, "kinds 为null");
            pageNum = pageNum == null ? super.pageNum : pageNum;
            pageSize = pageSize == null ? super.pageSize : pageSize;
            List<UserOrderOutInfo> info = userOrderService.findUserAllOrder(userId, pageNum, pageSize, kinds);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }

    }

    /**
     * 我的订单详情
     *
     * @param orderId
     * @return
     */
    @ApiOperation(value = "2.我的订单详情", notes = "我的订单详情")
    @GetMapping(value = "order/detail")
    public BaseResult listOrderDetail(String orderId) {
        try {
            MyAssert.notNullObject(orderId, "orderId 为null");
            UserOrderMoreInfo info = userOrderService.findUserOrderDetail(orderId);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }


    /**
     * 取消订单
     *
     * @param orderId
     * @param reason
     * @return
     */
    @ApiOperation(value = "3.取消订单", notes = "取消订单")
    @GetMapping(value = "order/cancelIt")
    public BaseResult cancelOrder(String userId, String orderId, String reason) {
        try {
            MyAssert.notNullObject(userId, "userId 为null");
            MyAssert.notNullObject(orderId, "orderId 为null");
            MyAssert.notNullObject(reason, "reason 为null");
            int info = userOrderService.doCancelOrder(userId, orderId, reason);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }


    /**
     * 取消订单
     *
     * @param userId
     * @param orderId
     * @return
     */
    @ApiOperation(value = "4.删除订单", notes = "删除订单")
    @GetMapping(value = "order/delete")
    public BaseResult delOrder(String userId, String orderId) {
        try {
            MyAssert.notNullObject(userId, "userId 为null");
            MyAssert.notNullObject(orderId, "orderId 为null");
            int info = userOrderService.doDelOrder(orderId, userId);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }


    /**
     * 物流详情
     *
     * @param orderId
     * @return
     */
    @ApiOperation(value = "5.物流详情", notes = "物流详情")
    @GetMapping(value = "order/expressInfo")
    public BaseResult findOrderExpressInfo(String orderId) {
        try {
            MyAssert.notNullObject(orderId, "orderId 为null");
            Map<String, Object> info = userOrderService.findOrderExpressInfo(orderId);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }

    /**
     * 物流详情
     *
     * @param orderId
     * @return
     */
    @ApiOperation(value = "5.5 物流详情列表", notes = "物流详情")
    @GetMapping(value = "order/expressDetail")
    public BaseResult findOrderExpressDetail(String orderId) {
        try {
            MyAssert.notNullObject(orderId, "orderId 为null");
            Map<String, Object> info = userOrderService.findOrderExpressDetail(orderId);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }


    /**
     * 更换订单物品
     *
     * @param orderId
     * @param what    0,换货,1,退货
     * @return
     */
    @ApiOperation(value = "6.更换订单物品", notes = "更换订单物品")
    @PostMapping(value = "order/exchange")
    public BaseResult exchangeOrder(String orderId, Integer what, String reason, String[] pics) {
        try {
            MyAssert.notNullObject(orderId, "orderId 为null");
            MyAssert.notNullObject(what, "what 为null");
            MyAssert.notNullObject(reason, "reason 为null");
            MyAssert.notNullArray(pics, "pics 为null");
            int info = userOrderService.doExchangeOrder(orderId, what, reason, pics);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }

    /**
     * 确认收货
     *
     * @param orderId
     * @return
     */
    @ApiOperation(value = "7.确认收货", notes = "确认收货")
    @GetMapping(value = "order/confirm")
    public BaseResult confirmOrder(String orderId) {
        try {
            MyAssert.notNullObject(orderId, "orderId 为null");
            int info = userOrderService.doConfirmOrder(orderId);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }


    @ApiOperation(value = "8.立即购买,生成订单", notes = "立即购买,生成订单")
    @PostMapping(value = "order/gen2")
    public BaseResult generateOrder2(@RequestBody OrderParam orderParam, HttpServletRequest request) {
        try {
            beforeAopRepeat(">>>".concat(orderParam.toString()));
            UserOrderFinalInfo info = userOrderService.doGenOrder(orderParam);
            int channel = info.getChannel();
            if (channel == 1 && info.getNeedPay() == 0) {
                BaseResult baseResult = toWikiH5Pay(request, info.getOrderId(), info.getUserId());
                return baseResult;
            }

            //下单完成，修改优先地址
            UserOrder userOrder = userOrderService.findUserOrderById(info.getOrderId());
            //先把所有的地址初始化
            userAddressService.resetUserPriorityAddress(info.getUserId());
            String addressId = userOrder.getAddressId();
            //设置地址优先级
            userAddressService.updateUserPriorityAddress(addressId);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }


    /**
     * 支付订单
     *
     * @param orderId
     * @param userId
     * @return
     */
    @ApiOperation(value = "9.支付订单", notes = "支付订单")
    @GetMapping(value = "order/payIt")
    public BaseResult toPayIt(String orderId, String userId, HttpServletRequest request) {
        try {
            MyAssert.notNullObject(orderId, "orderId 为null");
            MyAssert.notNullObject(userId, "userId 为null");
            beforeAopRepeat(">>>".concat(orderId.concat(userId)));
            Object info = userOrderService.doWXMiniPay(orderId, userId, request.getAttribute("clientIP").toString());
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }

    /**
     * 上传退款图片
     *
     * @param request
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "10.上传退款图片")
    @RequestMapping(value = "order/upFile", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "上传用户ID，", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "file", value = "上传文件，", paramType = "form", required = true, dataType = "file")
    })
    public BaseResult upload(HttpServletRequest request) throws IOException {
        try {
            BaseResult success = BaseResult.Builder.SUCC();
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = multipartRequest.getFile("file");
            logger.info("上传文件开始,fileName:{}", file.getOriginalFilename());
            String fileType = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            String fullPath = "kmzx/" + generateFileName(fileType);
            asyncUpload(fullPath, file.getInputStream());
            success.setData(qiNiuConfig.getDomainHost() + fullPath);
            return success;
        } catch (Exception e) {
            BaseResult fail = BaseResult.Builder.FAILServer().setData(null);
            fail.setErrMsg("文件异常");
            e.printStackTrace();
            logger.error("消息:{},{}", e.getMessage(), e.getCause());
            return fail;
        }
    }


    @ApiOperation(value = "11.获取退款订单", notes = "获取退款订单")
    @GetMapping(value = "userOrder/getBackOrder")
    public BaseResult findOrderBackInfo(String orderId) {
        try {
            MyAssert.notNullObject(orderId, "orderId 为null");
            OrderBackInfo info = userOrderService.findSubOrderBack(orderId);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }


    @ApiOperation(value = "12.直升物品下单", notes = "12.直升物品下单")
    @PostMapping(value = "order/genFast")
    public BaseResult generateFastOrder(@RequestBody OrderParam orderParam, HttpServletRequest request) {
        try {
            beforeAopRepeat(">>>".concat(orderParam.toString()));
            UserOrderFinalInfo info = userOrderService.doGenFastOrder(orderParam);
            if (info.getChannel() == 1 && info.getNeedPay() == 0) {
                BaseResult baseResult = toWikiH5Pay(request, info.getOrderId(), info.getUserId());
                return baseResult;
            }

            //下单完成，修改优先地址
            UserOrder userOrder = userOrderService.findUserOrderById(info.getOrderId());
            //先把所有的地址初始化
            userAddressService.resetUserPriorityAddress(info.getUserId());
            String addressId = userOrder.getAddressId();
            //设置地址优先级
            userAddressService.updateUserPriorityAddress(addressId);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(info);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }


    /**
     * 微信H5支付
     *
     * @param orderId
     * @param userId
     * @return
     */
    @ApiOperation(value = "13.微信H5支付", notes = "微信H5支付")
    @GetMapping(value = "order/wikiH5Pay")
    public BaseResult toWikiH5Pay(HttpServletRequest request, String orderId, String userId) {
        try {
            MyAssert.notNullObject(orderId, "orderId 为null");
            MyAssert.notNullObject(userId, "userId 为null");
            beforeAopRepeat(">>>".concat(orderId.concat(userId)));
            String clientIP = request.getAttribute("clientIP").toString();

            WikiH5PayResponse h5Pay = userOrderService.wikiH5Pay(orderId, userId, clientIP);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(h5Pay);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }


    /**
     * 用户实名信息,回显
     *
     * @param userId
     * @return
     */
    @ApiOperation(value = "14.用户实名信息,回显", notes = "用户实名信息,回显")
    @GetMapping(value = "order/cert")
    public BaseResult findLatestInfo(String userId) {
        try {
            MyAssert.notNullObject(userId, "userId 为null");
            beforeAopRepeat(">>>".concat(userId.concat(userId)));
            UserCertInfo h5Pay = userOrderService.latestUserCertInfo(userId);
            BaseResult success = BaseResult.Builder.SUCC().initSuccData(h5Pay);
            return success;
        } catch (Exception e) {
            return handleException(e);
        }
    }


}
